const mongo = require("../../../mongodb/mongoose")
const util = require('../../../util/util')
const t = require('../../../util/token')
const user = 'user'
const buddy = 'buddy'
const result = {
  msg: 'user DAL [not run]',
  data: null,
}
// 通过openid查询user
function getUserByOpendId(oid) {
  return mongo.find(user,{openId:oid},{},{},{})
}

module.exports = {
  // 通过openid查询user信息，空则插入
  async getUserInfo(data) {
    let res = result
    let r = await getUserByOpendId(data.openid)
    if (util.isNull(r)) {
      r = await mongo.insertMany(user,{openId: data.openid,name: '微信用户Ta',createTime: new Date().zoneDate()})
      if (r.writeErrors) {
        if (r.writeErrors[0].err.errmsg.indexOf('openId_1 dup key') >= 0)
          res.msg = '用户已存在'
        else 
          res.msg = r.writeErrors[0].err.errmsg
      } else {
        if (r.errors) {
          if (r.errors.openId) res.msg = r.errors.openId.message
          if (r.errors.name) res.msg = r.errors.name.message
          if (r.errors.avatar) res.msg = r.errors.avatar.message
        } else {
          res.data = r
          res.msg = 'success'
        }
      }
    } else {
      res.data = r
      res.msg = 'success'
    }
    if (res.msg == 'success') {
      let userInfo = {}
      userInfo.openId = data.openid
      userInfo.session_key = data.session_key
      res.data.push({session_key: data.session_key,token: t.setToken(userInfo)})
    }
    return res
  },
  // 通过openid查询user信息
  async getUserByOid(data) {
    let res = result
    let r = await getUserByOpendId(data.openId)
    if (util.isNull(r)) {
      res.msg = '无此用户'
    } else {
      if (data.flag == 'USER_LOGIN') {
        let userInfo = {}
        userInfo.openId = data.openid
        r.push({token: t.setToken(userInfo)})
      }
      res.msg = 'success'
    }
    res.data = r
    return res
  },
  // 设置用户昵称和头像
  async setUser(data) {
    let res = result
    let updatejson = {}
    if (!util.isNull(data.name)) updatejson.name = data.name
    if (!util.isNull(data.avatar)) updatejson.avatar = data.avatar
    let r = await mongo.updateOne(user,{openId:data.openId},{$set: updatejson})
    if (r.modifiedCount <= 0) {
      res.msg = '未修改任何记录'
    } else {
      if (r.errors) {
        if (r.errors.openId) res.msg = r.errors.openId.message
        if (r.errors.name) res.msg = r.errors.name.message
        if (r.errors.avatar) res.msg = r.errors.avatar.message
      } else {
        res.data = updatejson
        res.msg = 'success'
      }
    }
    return res
  },
  // 获取user列表
  async getUsers(data) {
    let res = result
    let sort = {'createTime':-1}
    let kw = data.keyWords.trim()
    let ks = []
    ks.push({name: new RegExp(kw, 'i')})
    // ks.push({openId: new RegExp(data.keyWords, 'i')})
    let filter = {$or: ks}
    if (util.isNull(kw)) filter = {openId: {$ne: data.adminOpenId}}
    let paging = {}
    paging.index = data.indexPage || 1
    paging.size = data.pageSize || 0
    let r = await mongo.find(user,filter,{},sort,paging)
    if (data.adminOpenId && paging.index == 1 && util.isNull(kw)) {
      let sr = await mongo.find(user,{openId: data.adminOpenId},{},{},{})
      if (sr && sr[0]) r.unshift(sr[0])
    }
    res.data = r
    res.msg = 'success'
    return res
  },
  // 按openid获取朋友列表
  async getBuddyByOpenId(data) {
    let res = result
    let oid = data.openId
    let r = await mongo.getBuddysByOid(oid)
    res.data = r
    res.msg = 'success'
    return res
  },
  // 绑定成为朋友
  async setBuddy(data) {
    let res = result
    let oid = data.openId
    let buddyId = data.buddyId
    let r = await mongo.find(user,{_id: buddyId},{},{},{})
    if (r && r[0].openId) {
      if (r[0].openId == oid) {
        res.msg = '不能添加自己'
      } else {
        let arr = []
        arr.push({openId: oid,buddyOpenId: r[0].openId,createTime: new Date().zoneDate()})
        arr.push({openId: r[0].openId,buddyOpenId: oid,createTime: new Date().zoneDate()})
        let r0 = await mongo.insertMany(buddy,arr)
        if (r0.writeErrors) {
          if (r0.writeErrors[0].err.errmsg.indexOf('openId_1_buddyOpenId_1 dup key') >= 0)
            res.msg = '已经添加为朋友'
          else 
            res.msg = r0.writeErrors[0].err.errmsg
        } else {
          if (r0.errors) {
            if (r0.errors.openId) res.msg = r0.errors.openId.message
            if (r0.errors.buddyOpenId) res.msg = r0.errors.buddyOpenId.message
          } else {
            res.data = r
            res.msg = 'success'
          }
        }
      }
    }
    return res
  },
  // 删除朋友
  async delBuddy(data) {
    let res = result
    let oid = data.openId
    let buddyOId = data.buddyOId
    let r1 = await mongo.deleteMany(buddy,{openId: oid,buddyOpenId: buddyOId})
    let r2 = await mongo.deleteMany(buddy,{openId: buddyOId,buddyOpenId: oid})
    if (r1.deletedCount <= 0) {
      res.msg = '朋友删除失败'
    } else if (r2.deletedCount <= 0) {
      res.msg = '朋友列表中删除失败'
    } else {
      res.msg = 'success'
    }
    return res
  }
}